var M=require("ming_node");
var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();

M.sseServer = function () {
    //sse 心跳
    function headBeat(){
        try {
            let clientIdList= Array.from(M._sseClientMap.keys());
            for (let i=0;i<clientIdList.length;i++){
                let clientId= clientIdList[i];
                let res= M._sseClientMap.get(clientId).res;
                let r=  res.write(': \n\n');
                if(!r){
                    M._sseClientMap.delete(clientId);
                    M["_sse_disconnect"](clientId);
                }
            }
        }catch (e){
            console.error(e);
        }
    }

    M["_sse_connection"]=(clientId)=>{
        console.log(clientId+" connection")
    }

    M["_sse_disconnect"]=(clientId)=>{
        console.log(clientId+" disconnect")
    }

    M["_sse_send"]=(clientId,msg)=>{
        // console.log("sse_send",clientId,msg)
    }

    event.on('sseSendMsg', function (sendData,clientId,eventName="slide",id=+new Date()) {
        let sendObj={event:eventName,id:id,data:sendData,retry:10000}
        if(!clientId){
            let clientIdList= Array.from(M._sseClientMap.keys())
            for (let i=0;i<clientIdList.length;i++){
                let clientId= clientIdList[i];
                let res=M._sseClientMap.get(clientId)?M._sseClientMap.get(clientId).res:null;
                if(res==null){
                    continue;
                }
                res.write(`event: ${sendObj.event}\n`); // 事件类型
                res.write(`id: ${sendObj.id}\n`); // 消息 ID
                res.write(`data: ${sendObj.data}\n`); // 消息数据
                res.write(`retry: ${sendObj.retry}\n`); // 重连时间
                res.write('\n\n'); // 消息结束
            }
        }else {
            let res=M._sseClientMap.get(clientId)?M._sseClientMap.get(clientId).res:null;
            if(res==null){
                return
            }
            res.write(`event: ${sendObj.event}\n`); // 事件类型
            res.write(`id: ${sendObj.id}\n`); // 消息 ID
            res.write(`data: ${sendObj.data}\n`); // 消息数据
            res.write(`retry: ${sendObj.retry}\n`); // 重连时间
            res.write('\n\n'); // 消息结束
        }
        M["_sse_send"](clientId,sendObj);
    })
    setInterval(() => {
        headBeat();
    }, M._sseHeatTime);

    let app = function (req, res) {
        headBeat();
        let clientId=req.params.clientId;
        let connectionRes= M["_sse_connection"](clientId);
        if(connectionRes==false){
            return;
        }
        M._sseClientMap.set(clientId,{res});
        res.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',
        });
    };
    app.send = function (msg,clientId,eventName,id) {
        event.emit('sseSendMsg', msg,clientId,eventName,id);
    }

    app.call = function (eventName,msg,clientId,id) {
        event.emit('sseSendMsg', msg,clientId,eventName,id);
    }

    app.set = function (k, v) {
        M["_" + k] = v;
    }

    app.listen = function (port) {
        let serverObj = http.createServer(app).listen(port);
        app.serverObj = serverObj;
        console.log("SSE Server listen on port:" + port);
        return app;
    }
    return app;
}